package biznussoft.metercor.fragments;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.adapter.SiteAdapter;
import biznussoft.metercor.adapter.SiteInventoryAdapter;
import biznussoft.metercor.listeners.GlobalListener;
import biznussoft.metercor.model.InventoryModel;
import biznussoft.metercor.model.SiteInventoryModel;
import biznussoft.metercor.model.SiteModel;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class WarehouseDetailsFragment extends BaseFragment implements OnItemClickListener {
	private   Dialog progressDialog ;
	private LinearLayout warehouseDetails,siteDetails;
	private TextView tvSiteName,tvCity,tvState,tvStreet,tvCountry,tvZip,tvSitePhone,tvSiteFax,tvEmail,tvWebsite;
	private TextView tvWareHouseName,tvDescription,tvGeoLocation;
	private ListView lv,inventoryListView;
	private ArrayList<SiteModel> list ;
	private GlobalListener listener;
	private RestClient client;
	private SiteModel bean ;
	static ArrayList<SiteInventoryModel> inventoryList;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.warehouse_fragment, null);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
	}
	
	@Override
	public void onAttach(Activity activity) {          
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (GlobalListener) getActivity();
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem addAccount = menu.add("Inventory");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.add); 
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	
	@Override
	 public boolean onOptionsItemSelected(MenuItem item) {
		/* if(item.getTitle().equals("Logout")){
			 SalesforceSDKManager.getInstance().logout(getActivity());}*/
		 if(item.getTitle().equals("Inventory")){
			 listener.onGetContacts(0,bean.getSiteId());
		 }
		
		 return super.onOptionsItemSelected(item);
	 }
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		client =  HomeActivity.mActivity.client;
		tvWareHouseName = (TextView) getView().findViewById(R.id.tvWarehouseName);
		tvDescription = (TextView) getView().findViewById(R.id.tvDescription);
		tvGeoLocation = (TextView) getView().findViewById(R.id.tvgeoLocation);
		lv = (ListView) getView().findViewById(R.id.siteListview);
		lv.setOnItemClickListener(this);
		
		inventoryListView = (ListView) getView().findViewById(R.id.invetoryList);
		inventoryListView.setOnItemClickListener(this);
		
		warehouseDetails = (LinearLayout) getView().findViewById(R.id.llayoutWarehouseDetails);
		siteDetails = (LinearLayout) getView().findViewById(R.id.llayoutSiteDetails);
		tvSiteName = (TextView) getView().findViewById(R.id.tvSiteName);
		tvCity = (TextView) getView().findViewById(R.id.tvCity);
		tvState = (TextView) getView().findViewById(R.id.tvState);
		tvStreet = (TextView) getView().findViewById(R.id.tvStreet);
		tvCountry = (TextView) getView().findViewById(R.id.tvCountry);
		tvZip = (TextView) getView().findViewById(R.id.tvZip);
		tvSitePhone = (TextView) getView().findViewById(R.id.tvSitePhone);
		tvSiteFax = (TextView) getView().findViewById(R.id.tvSiteFax);
		tvEmail = (TextView) getView().findViewById(R.id.tvSiteEmail);
		tvWebsite = (TextView) getView().findViewById(R.id.tvSiteWebsite);
		
	}
	
	
	public void getWarehouseDetails(int Position){      
		
		InventoryModel mobel = WarehouseFragment.InventoryList.get(Position);
		tvWareHouseName.setText(mobel.getName());
		tvDescription.setText(mobel.getDescription());
		tvGeoLocation.setText(mobel.getGeoLocation());               
		list = WarehouseFragment.inventorySiteList.get(mobel.getId());
		SiteAdapter adapter = new SiteAdapter(getActivity(),list);
		lv.setAdapter(adapter);
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
		
		switch (arg0.getId()) {
		case R.id.siteListview:
			displaySiteDetails(position);
			break;
		case R.id.invetoryList:
			listener.onGetContacts(position, "SiteInventory");
			break;
		default:
			break;
		}
		
		
	}
	
	
	private void displaySiteDetails(int position){
		setHasOptionsMenu(true);
		warehouseDetails.setVisibility(View.GONE);
		siteDetails.setVisibility(View.VISIBLE);
		bean = list.get(position);
		tvSiteName.setText(bean.getSiteName());
		tvCity.setText(bean.getCity());         
		tvState.setText(bean.getState());
		tvStreet.setText(bean.getStreet());
		tvCountry.setText(bean.getCountry());    
		tvZip.setText(bean.getZip());
		tvSitePhone.setText(bean.getPhone());              
		tvSiteFax.setText(bean.getFax());
		tvEmail.setText(bean.getEmail());
		tvWebsite.setText(bean.getWebsite());
		inventory(bean.getSiteId());
		 progressDialog = biznussoft.metercor.utils.ProgressDialog.getInstance().createProgressDialog(getActivity());
		 progressDialog.setCanceledOnTouchOutside(false);
         progressDialog.show();             
		
	}
	
	public void inventory(String siteId){
		

		try{
			String accounts = "select Id,FConnect__Item__c,FConnect__Name__c,FConnect__Site__c,FConnect__Quantity__c,FConnect__Price__c,FConnect__Serial_ID__c,FConnect__Lot_ID__c,FConnect__Discription__c from FConnect__Inventory__c where FConnect__Site__c ="+"'"+siteId+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
			            
			            
								JSONObject jsonObject1 = new JSONObject(result.asString());
								
								JSONArray jsonArray = jsonObject1.getJSONArray("records");
								
								inventoryList = new ArrayList<SiteInventoryModel>();
								Gson _gson = new Gson();
								for(int i=0; i< jsonArray.length(); i++)
								{
									if(!jsonArray.isNull(i)){
							 	   		SiteInventoryModel bean = _gson.fromJson(jsonArray.getString(i), SiteInventoryModel.class);
							 	   	inventoryList.add(bean);
							 	   		}
								}     
								
								
								progressDialog.dismiss();
							if(inventoryList.size()>0){
								SiteInventoryAdapter adapter = new SiteInventoryAdapter(getActivity(), inventoryList);
								inventoryListView.setAdapter(adapter);
								 
							}
								
							
						
					
					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	
	}


}
